﻿namespace EffectsLib
{
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Effects;

    /// <summary>
    /// Greyscale effect.
    /// </summary>
    public class GreyscaleEffect : ShaderEffect
    {
        /// <summary>
        /// Dependency property for Input.
        /// </summary>
        public static readonly DependencyProperty InputProperty =
            ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(GreyscaleEffect), 0 /* assigned to sampler register S0 */);
        public Brush Input
        {
            get { return (Brush)GetValue(InputProperty); }
            set { SetValue(InputProperty, value); }
        }

        public static readonly DependencyProperty DesaturationFactorProperty = DependencyProperty.Register("DesaturationFactor", typeof(double), typeof(GreyscaleEffect), new UIPropertyMetadata(0.0, PixelShaderConstantCallback(0), CoerceDesaturationFactor));
        public double DesaturationFactor
        {
            get { return (double)GetValue(DesaturationFactorProperty); }
            set { SetValue(DesaturationFactorProperty, value); }
        }

        protected static object CoerceDesaturationFactor(DependencyObject d, object value)
        {
            GreyscaleEffect effect = (GreyscaleEffect)d;
            double newDesatFactor = (double)value;

            if (newDesatFactor < 0.0 || newDesatFactor > 1.0)
            {
                return effect.DesaturationFactor;
            }

            return newDesatFactor;
        }

        /// <summary>
        /// PixelShader for this effect.
        /// </summary>
        private static PixelShader pixelShader = new PixelShader();

        /// <summary>
        /// Static constructor - Create a PixelShader for all GreyscaleEffect instances. 
        /// </summary>
        static GreyscaleEffect()
        {
            pixelShader.UriSource = Global.MakePackUri("Bytecode/Greyscale.ps");
        }

        /// <summary>
        /// Constructor - Assign the PixelShader property and set the shader parameters to default values.
        /// </summary>
        public GreyscaleEffect()
        {
            this.PixelShader = pixelShader;
            UpdateShaderValue(InputProperty);
            UpdateShaderValue(DesaturationFactorProperty);
        }
       
    }
}
